package com.pf.commom.aop;

import com.pf.commom.annotation.PrintLog;
import com.pf.utils.JacksonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.io.InputStreamSource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/8/28
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Pointcut("execution(public * com.pf.controller..*.*(..))")
    public void printLog() {

    }

    @Around("printLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURI = request.getRequestURI();
        List<Object> methodArgs = Arrays.stream(proceedingJoinPoint.getArgs())
                .filter(a -> !(a instanceof HttpServletResponse) && !(a instanceof InputStreamSource))
                .collect(Collectors.toList());
        Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
        PrintLog annotation = method.getAnnotation(PrintLog.class);
        //打印目标方法入参
        if (annotation == null || (annotation != null && annotation.reqPrint())) {
            log.info(">>>>> url:{}, args:{}", requestURI, JacksonUtils.toJsonString(methodArgs));
        }
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        long endTime = System.currentTimeMillis();
        //打印目标方法返回结果
        if (log.isDebugEnabled() || (annotation != null && annotation.resPrint())) {
            log.info(">>>>> url:{}, return result:{}", requestURI, JacksonUtils.toJsonString(result));
        }
        log.info(">>>>> url execute finish ! method:{},execute time：{}", requestURI, endTime - startTime);
        return result;
    }
}
